package com.actions;

import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import com.bean.ProcureInquiry;
import com.bean.ProcureProduct;
import com.bean.Suin;
import com.bean.SupplierProduct;
import com.bean.Usin;
import com.opensymphony.xwork2.ActionSupport;
import com.serviceImpl.ProcureInquiryServiceImpl;
import com.serviceImpl.SupplierProductServiceImpl;
import com.serviceImpl.UtilSupport;

public class ProcureInquiryAction extends ActionSupport {

	private ProcureInquiryServiceImpl procureInquiryBiz;
	private SupplierProductServiceImpl supplierProductBiz;
	private List<ProcureInquiry> suinInquiryList;	//供应商询价列表
	private ProcureInquiry proInquiry;
	private UtilSupport util ;
	private boolean flag;

	private int offset;			//当前页
	private int pageSize=10;
	private int totalcount;		// 总记录数
	private int totalpage; 		// 总页数

	private String qproductCode;//款号
	private Timestamp qsendTime;//创建时间
	private Timestamp qendTime;//创建时间
	private Integer qstatus;//状态

	private String quoteInfo;
	private Double wprice;

	public ProcureInquiryAction() {
		suinInquiryList = new ArrayList<ProcureInquiry>();
	}

	public ProcureInquiryServiceImpl getProcureInquiryBiz() {
		return procureInquiryBiz;
	}

	public void setProcureInquiryBiz(ProcureInquiryServiceImpl procureInquiryBiz) {
		this.procureInquiryBiz = procureInquiryBiz;
	}

	public List<ProcureInquiry> getSuinInquiryList() {
		return suinInquiryList;
	}

	public void setSuinInquiryList(List<ProcureInquiry> suinInquiryList) {
		this.suinInquiryList = suinInquiryList;
	}

	public ProcureInquiry getProInquiry() {
		return proInquiry;
	}

	public void setProInquiry(ProcureInquiry proInquiry) {
		this.proInquiry = proInquiry;
	}

	public UtilSupport getUtil() {
		return util;
	}

	public void setUtil(UtilSupport util) {
		this.util = util;
	}

	public boolean isFlag() {
		return flag;
	}

	public void setFlag(boolean flag) {
		this.flag = flag;
	}

	public int getOffset() {
		return offset;
	}

	public void setOffset(int offset) {
		this.offset = offset;
	}

	public int getTotalcount() {
		return totalcount;
	}

	public void setTotalcount(int totalcount) {
		this.totalcount = totalcount;
	}

	public int getTotalpage() {
		return totalpage;
	}

	public void setTotalpage(int totalpage) {
		this.totalpage = totalpage;
	}

	public String getQproductCode() {
		return qproductCode;
	}

	public void setQproductCode(String qproductCode) {
		this.qproductCode = qproductCode;
	}

	public Timestamp getQsendTime() {
		return qsendTime;
	}

	public void setQsendTime(Timestamp qsendTime) {
		this.qsendTime = qsendTime;
	}

	public Timestamp getQendTime() {
		return qendTime;
	}

	public void setQendTime(Timestamp qendTime) {
		this.qendTime = qendTime;
	}

	public Integer getQstatus() {
		return qstatus;
	}

	public void setQstatus(Integer qstatus) {
		this.qstatus = qstatus;
	}

	public void setQuoteInfo(String quoteInfo) {
		this.quoteInfo = quoteInfo;
	}

	public SupplierProductServiceImpl getSupplierProductBiz() {
		return supplierProductBiz;
	}

	public void setSupplierProductBiz(SupplierProductServiceImpl supplierProductBiz) {
		this.supplierProductBiz = supplierProductBiz;
	}

	public Double getWprice() {
		return wprice;
	}

	public void setWprice(Double wprice) {
		this.wprice = wprice;
	}

	/**
	 * 获取供应商询价列表
	 * @return
	 */
	public String suinInquiryList(){
		HttpServletRequest request = ServletActionContext.getRequest();
		StringBuffer sqlbf = new StringBuffer("SELECT * from audit.procure_inquiry pi " +
				"INNER JOIN audit.procure_product p ON pi.proc_id = p.proc_id WHERE 0=0");

		StringBuffer querySql = new StringBuffer("");

		try {
			this.qproductCode = request.getParameter("qproductCode");
			if(qproductCode != null && !qproductCode.isEmpty()){
				qproductCode  = new String(qproductCode.trim().getBytes("ISO-8859-1"),"UTF-8");
				String query = " and p.product_code like '%"+qproductCode+"%'";
				querySql.append(query);
				sqlbf.append(query);
			}

			String status = request.getParameter("qstatus");
			if(status!=null&&!status.isEmpty()){
				this.qstatus = Integer.parseInt(status);
				String query = " and p.status = "+qstatus+"";
				querySql.append(query);
				sqlbf.append(query);
			}

			String sendTime=request.getParameter("qsendTime");
			String endTime=request.getParameter("qendTime");

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");// 设置时间显示格式

			if(sendTime!=null&&!sendTime.isEmpty()){
				//设置开始时间
				Date sDate = sdf.parse(sendTime);
				qsendTime = new Timestamp(sDate.getTime());

				if(endTime!=null&&!endTime.isEmpty()){
					//设置结束时间
					Date eDate = sdf.parse(endTime);
					qendTime = new Timestamp(eDate.getTime());

					querySql.append(" and pi.send_time between '"+qsendTime+"' and '"+qendTime+"'");
				}else{
					querySql.append(" and pi.end_time > '"+qsendTime+"'");
				}

			}else{
				if(endTime!=null&&!endTime.isEmpty()){
					//设置结束时间
					Date eDate = sdf.parse(endTime);
					qendTime = new Timestamp(eDate.getTime());

					querySql.append(" and pi.end_time < '"+qendTime+"'");
				}
			}

			String sql =sqlbf.toString() + querySql.toString();

			totalcount = util.getTotalCount(sql);

			totalpage = totalcount % pageSize == 0 ? totalcount / pageSize
					: totalcount / pageSize + 1;

			offset = getPageOffset();
			//表名
			String table="v_procure_inquiry";
			//主键
			String pk="pq_id";
			//排序字段
			String sort="send_time";
			//当前页数
			int PageNumber = offset+1;
			int PageSize = pageSize;
			if(querySql.toString().equals("")){
				querySql.append(" 0=0");
			}

			suinInquiryList = procureInquiryBiz.getSuinInquiryList(table, pk, sort, PageNumber, PageSize, querySql.toString());
		} catch (Exception e) {
			// TODO: handle exception
		}
		return "show";
	}

	// Added by JSL : 获取翻页偏移量(实际上是将要翻到的页面的页索引，页索引从 0 开始)
	private int getPageOffset() {
		HttpServletRequest request=ServletActionContext.getRequest();
		String ofst = request.getParameter("offset");
		int idx = 0;
		if(ofst!=null){
			idx = Integer.valueOf(ofst);
			idx = idx < 0 ? 0 : idx;                        // 超过第一页时，不再翻页
			idx = idx >= totalpage ? (totalpage-1) : idx;	// 超过最后一页时，不再翻页		
		}
		return idx;
	}

	/**
	 * 获取当前登录用户信息
	 */
	private String getCurrUser(){
		//获取session对象
		HttpServletRequest request=ServletActionContext.getRequest();
		HttpSession session=request.getSession();
		Usin loginuser=(Usin)session.getAttribute("pu");
		return null;
	}

	/**
	 * 获取选中询价单详情
	 * @return
	 */
	public String getQuoteInfo(){
		try {
			quoteInfo = new String(quoteInfo.trim().getBytes("ISO-8859-1"),"UTF-8");
			JSONObject quoteBean = JSONObject.fromObject(quoteInfo);
			proInquiry = new ProcureInquiry();
			int pqId = quoteBean.getInt("pqId");
			String blueprint = quoteBean.getString("blueprint").trim();//设计图
			int procCount = quoteBean.getInt("procCount");//采购数量

			String sysUser = quoteBean.getString("sysUser").trim();//发布人员

			String sendTime =  quoteBean.getString("sendTime").trim();//开始时间
			String endTime =  quoteBean.getString("endTime").trim();//结束时间
			String deliveryDate = quoteBean.getString("deliveryDate").trim();//结束时间

			String suid = quoteBean.getString("suid").trim();
			String productCode = quoteBean.getString("productCode").trim();

			ProcureProduct pp = new ProcureProduct();
			pp.setProductCode(productCode);
			pp.setBlueprint(blueprint);
			pp.setProcCount(procCount);
			pp.setSysUser(sysUser);
			SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA); 
			SimpleDateFormat sf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);

			deliveryDate = sf1.format(sf.parse(deliveryDate));
			sendTime = sf1.format(sf.parse(sendTime));
			endTime = sf1.format(sf.parse(endTime));

			pp.setDeliveryDate(Timestamp.valueOf(deliveryDate));

			proInquiry.setPqId(pqId);
			proInquiry.setSuid(suid);
			proInquiry.setEndTime(Timestamp.valueOf(endTime));
			proInquiry.setSendTime(Timestamp.valueOf(sendTime));
			proInquiry.setProcureProduct(pp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "quoteInfo";
	}

	/**
	 * 供应商报价
	 * @return
	 */
	public String supplierQuote(){
		try {
			JSONObject quoteBean = JSONObject.fromObject(quoteInfo);
			int pqId = quoteBean.getInt("pqId");
			String suid = quoteBean.getString("suid").trim();
			String productCode = quoteBean.getString("productCode").trim();
			
			//获取当前时间
			Date date = new Date();//创建一个时间对象，获取到当前的时间
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置时间显示格式
			String currentDate = sdf.format(date);// 将当前时间格式化为需要的类型

			SupplierProduct sproduct = new SupplierProduct();
			sproduct.setCreateTime(Timestamp.valueOf(currentDate));	//操作日期（当状态发生改变时改变）
			sproduct.setPrice(wprice);
			ProcureInquiry pi = new ProcureInquiry(pqId);
			Suin suin = new Suin();
			suin.setSuid(suid);
			sproduct.setProcureInquiry(pi);
			sproduct.setSuin(suin);
			sproduct.setProductCode(productCode);
			supplierProductBiz.saveSupproduct(sproduct);
			
			flag = true;
		} catch (Exception e) {
			flag = false;
		}
		
		return SUCCESS;
	}
}
